<template>
  <view class="customer-container">
    <!-- 新增按钮 -->
    <view class="action-bar">
      <button @click="showAddCustomerModal" class="action-button">新增客户</button>
    </view>

    <!-- 搜索框 -->
    <view class="search-bar">
      <input type="text" v-model="searchQuery" placeholder="搜索客户" class="search-input" />
      <button @click="searchCustomers" class="search-button">搜索</button>
    </view>

    <!-- 客户列表 -->
    <view class="customer-list">
      <!-- 空空如也提示 -->
      <view v-if="customers.length === 0" style='display: flex;align-items: center;justify-content: center;margin-top: 50px;'>
        <image src='../../Resources/Image/空空如也.png' style='width: 120px;height:120px;'></image>
      </view>
      <view v-for="(customer, index) in customers" :key="index" class="customer-item" style="height: 50px;">
        <view class="customer-info">
          <view class="customer-name">{{ customer.customer_name }}</view>
          <view class="customer-code">{{ customer.customer_no }}</view>
        </view>
        <view class="customer-actions">
		  <image src='../../Resources/Image/详细信息.png' style='width: 22px;height:22px;margin-right: 5px;' @click="showInfo(customer)"></image>
          <image src='../../Resources/Image/编辑.png' style='width: 25px;height:25px;margin-right: 5px;' @click="editCustomer(customer)"></image>
          <image src='../../Resources/Image/删除.png' style='width: 27px;height:27px;' @click="deleteCustomer(customer)"></image>
        </view>
      </view>
    </view>

    <!-- 新增客户弹窗 -->
    <view v-if="showModal" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">新建客户</text>
        </view>
        <view class="modal-body">
          <input type="text" v-model="newCustomer.customer_no" placeholder="客户标号" class="input-field" />
          <input type="text" v-model="newCustomer.customer_name" placeholder="客户名称" class="input-field" />
          <input type="text" v-model="newCustomer.customer_contact" placeholder="联系人" class="input-field" />
          <input type="text" v-model="newCustomer.customer_phone" placeholder="联系电话" class="input-field" />
          <input type="text" v-model="newCustomer.customer_address" placeholder="地址" class="input-field" />
          <picker mode="selector" :range="['合作中', '暂停合作', '终止合作']" @change="onCooperationStatusChange" :value="0">
            <view class="picker">{{ newCustomer.customer_status }}</view>
          </picker>
          <textarea v-model="newCustomer.remark" placeholder="备注" class="textarea-field"></textarea>
        </view>
        <view class="modal-footer">
          <button @click="submitCustomer" class="action-button">提交</button>
          <button @click="hideModal" class="action-button">取消</button>
        </view>
      </view>
    </view>
	
	
	<!-- 查看客户详细信息 -->
	<view v-if="showModalInfo" class="modal">
	  <view class="modal-content">
	    <view class="modal-header">
	      <text class="modal-title">查看客户详细信息</text>
	    </view>
	    <view class="modal-body">
	      <input type="text" v-model="newCustomer.customer_no" placeholder="客户标号" class="input-field" :disabled="true"/>
	      <input type="text" v-model="newCustomer.customer_name" placeholder="客户名称" class="input-field"  :disabled="true"/>
	      <input type="text" v-model="newCustomer.customer_contact" placeholder="联系人" class="input-field"  :disabled="true"/>
	      <input type="text" v-model="newCustomer.customer_phone" placeholder="联系电话" class="input-field"  :disabled="true"/>
	      <input type="text" v-model="newCustomer.customer_address" placeholder="地址" class="input-field"  :disabled="true"/>
	      <picker mode="selector" :range="['合作中', '暂停合作', '终止合作']" @change="onCooperationStatusChange" :disabled="true">
	        <view class="picker">{{ newCustomer.customer_status }}</view>
	      </picker>
	      <textarea v-model="newCustomer.remark" placeholder="备注" class="textarea-field" :disabled="true"></textarea>
	    </view>
	    <view class="modal-footer">

	      <button @click="hideModal" class="action-button">取消</button>
	    </view>
	  </view>
	</view>
	
	<!-- 修改客户详细信息 -->
	<view v-if="AlterModalInfo" class="modal">
	  <view class="modal-content">
	    <view class="modal-header">
	      <text class="modal-title">修改客户信息</text>
	    </view>
	    <view class="modal-body">
	      <input type="text" v-model="newCustomer.customer_no" placeholder="客户标号" class="input-field" />
	      <input type="text" v-model="newCustomer.customer_name" placeholder="客户名称" class="input-field"  />
	      <input type="text" v-model="newCustomer.customer_contact" placeholder="联系人" class="input-field"  />
	      <input type="text" v-model="newCustomer.customer_phone" placeholder="联系电话" class="input-field" />
	      <input type="text" v-model="newCustomer.customer_address" placeholder="地址" class="input-field" />
	      <picker mode="selector" :range="['合作中', '暂停合作', '终止合作']" @change="onCooperationStatusChange">
	        <view class="picker">{{ newCustomer.customer_status }}</view>
	      </picker>
	      <textarea v-model="newCustomer.remark" placeholder="备注" class="textarea-field"></textarea>
	    </view>
	    <view class="modal-footer">
		<button @click="AlertCustomer" class="action-button">提交</button>
	      <button @click="hideModal" class="action-button">取消</button>
	    </view>
	  </view>
	</view>
	
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { config } from '../../config';
import { TokenStore } from '../../Store/TokenStore';
import { LoginState } from '../../util/LoginSate';
import { onPullDownRefresh , onReachBottom } from "@dcloudio/uni-app";

// 客户数据 用于搜索数据的展现
let customers = ref([
	
]);

//分片数据
let pageinfo = ref( {
	size:10,
	page:1
})

//全部客户数据
let AllCustomer = ref([]);




onMounted(()=>{
	if(!LoginState()){
		uni.showToast({
		  title: '登录失效',
		  icon: 'error'
		});
		uni.redirectTo({
			url:"/pages/index/index"
		})
		return ;
	}
	AllCustomers()
})

//---------------------------------------下拉刷新/到底加载----------------------------------------------

onPullDownRefresh(()=>{
	pageinfo.value.page = 1;
	AllCustomer.value = []
	customers.value = []
	AllCustomers()
	uni.stopPullDownRefresh()
})

onReachBottom(()=>{
	AllCustomers()
})

//--------------------------------------------------------------------------------------------


let showModalInfo = ref(false);

let AlterModalInfo = ref(false);

let select = ['合作中', '暂停合作', '终止合作'];

function AllCustomers(){
	uni.request({
		url:`${config.baseURL}/Customer/AllCustoms`,
		method:'POST',
		data:pageinfo.value,
		header: {
			'content-type': 'application/json', // 设置请求头为 JSON
			'Authorization': TokenStore().token
		},
		success:(res)=>{
			if(res.data.data === "error"){
				uni.showToast({
				  title: '数据库错误',
				  icon: 'error'
				});
			}
			else if(res.data.data === '令牌过期'){
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
			else {
				let data = JSON.parse(res.data.data);
				//追加
				customers.value.push(...data)
				AllCustomer.value.push(...data)
				//更新数据
				pageinfo.value.page+=pageinfo.value.size
			}
		}
	})
}

//修改客户信息
function AlertCustomer(){
	uni.request({
		url:`${config.baseURL}/Customer/AlterCustomers`,
		method:'POST',
		data:newCustomer.value,
		header: {
			'content-type': 'application/json', // 设置请求头为 JSON
			'Authorization': TokenStore().token
		},
		success:(res)=>{
			if(res.data.data === '1'){
				uni.showToast({
				  title: "修改成功",
				  icon: 'success'
				});
				pageinfo.value.page = 1;
				AllCustomer.value = []
				customers.value = []
				AllCustomers()
				hideModal()
			}
			else if(res.data.data === 'error'){
				uni.showToast({
				  title: "数据库错误",
				  icon: 'error'
				});
			}
			else if(res.data.data === '令牌过期'){
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
			else {
				uni.showToast({
				  title: "系统繁忙",
				  icon: 'error'
				});
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	})
}

//显示客户信息
function showInfo(customer){
	newCustomer.value = { ...customer };
	showModalInfo.value = true;
}

// 新增客户弹窗状态
const showModal = ref(false);
const newCustomer = ref({ id : 111,customer_no: '', customer_name: '', customer_contact: '', customer_phone: '', customer_address: '', customer_status: '合作中', remark: '' });

// 搜索框数据
const searchQuery = ref('');

// 显示新增客户弹窗
const showAddCustomerModal = () => {
	
  showModal.value = true;
};

// 隐藏新增客户弹窗
const hideModal = () => {
	showModalInfo.value = false;
  showModal.value = false;
  AlterModalInfo.value = false;
  Object.keys(newCustomer.value).forEach(key => {
    newCustomer.value[key] = '';
  });
  newCustomer.value.customer_status = '合作中'
  AllCustomers()
};

// 提交新增客户
const submitCustomer = () => {
	
	if (Object.values(newCustomer).some(value => value === '')) {
	  uni.showToast({
	    title: "请填写所有字段",
	    icon: 'error'
	  });
		return ;
	}
	
	uni.request({
		url:`${config.baseURL}/Customer/AddCustomers`,
		method:'POST',
		data:newCustomer.value,
		header: {
			'content-type': 'application/json', // 设置请求头为 JSON
			'Authorization': TokenStore().token
		},
		success:(res)=>{
			console.log(res.data.data)
			if(res.data.data === '1'){
				uni.showToast({
				  title: "添加成功，请下拉刷新后查看",
				  icon: 'none'
				});
				hideModal();
			}
			else if(res.data.data === 'error'){
				uni.showToast({
				  title: "数据库错误",
				  icon: 'error'
				});
			}
			else if(res.data.data === '0'){
				uni.showToast({
				  title: "系统繁忙",
				  icon: 'error'
				});
			}
			else if(res.data.data === '令牌过期'){
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	})

};

// 编辑客户
const editCustomer = (customer) => {
  // 这里可以弹出编辑框，或者跳转到编辑页面
  console.log('编辑客户', customer);
  newCustomer.value = { ...customer }
  console.log("赋值成功"+JSON.stringify(newCustomer.value))
  AlterModalInfo.value = true;
};

// 删除客户
const deleteCustomer = (customer) => {
	uni.request({
		url:`${config.baseURL}/Customer/DeleteCustomers`,
		method:'POST',
		data:customer,
		header: {
			'content-type': 'application/json', // 设置请求头为 JSON
			'Authorization': TokenStore().token
		},
		success:(res)=>{
			if(res.data.data === '令牌过期'){
				uni.showToast({
				  title: '请重新登录',
				  icon: 'error'
				});
			}
			else if(res.data.data === 'error'){
				uni.showToast({
				  title: '数据库错误',
				  icon: 'error'
				});
			}
			else {
				uni.showToast({
				  title: '删除成功',
				  icon: 'success'
				});
				pageinfo.value.page = 1;
				AllCustomer.value = []
				customers.value = []
				AllCustomers()
			}
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error'
			});
		}
	})
};

// 合作状态改变事件
const onCooperationStatusChange = (e) => {
  newCustomer.value.customer_status =  select[e.detail.value];
  console.log("状态改变"+newCustomer.value.customer_status);
};

// 搜索客户
const searchCustomers = () => {
  
  if(searchQuery.value === ''){
	  customers.value = AllCustomer.value;
	  return ;
  }
  
  const searchedGoods = AllCustomer.value.filter(item => item.customer_name === searchQuery.value);
  console.log("查询出数据"+JSON.stringify(searchedGoods))
  customers.value = searchedGoods
};
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #eef7f6; /* 浅蓝色背景 */
  height: 100vh;
}

.action-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 80%;
  height: 40px;
  background-color: #3e92cc; /* 蓝色 */
  color: white;
  transition: background-color 0.3s;
}

.action-button:hover {
  background-color: #3079a4;
}

.search-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.search-input {
  padding: 10px;
  width: 70%;
  border: 1px solid #eaeaea;
  border-radius: 5px;
  margin-right: 10px;
}

.search-button {
  border: none;
  border-radius: 5px;
  width: 20%;
  cursor: pointer;
  height: 40px;
  background-color: #007aff; /* 蓝色 */
  color: white;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #0051b3;
}

.customer-list {
  width: 100%;
  margin: 0 auto;
}

.customer-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.customer-item:hover {
  transform: translateY(-5px);
}

.customer-info {
  display: flex;
  align-items: center;
}

.customer-name {
  margin-right: 10px;
  color: #333;
}

.customer-code {
  color: #666;
}

.customer-actions {
  display: flex;
  align-items: center;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
  font-size: 18px;
  font-weight: bold;
  color: #007aff;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.modal-body {
  margin: 20px 0;
}

.input-field, .textarea-field {
  width: 95%;
  padding: 10px;
  margin-bottom: 20px;
  border: 1px solid #eaeaea;
  border-radius: 5px;
  height: 20px;
}

.picker {
  padding: 10px;
  background-color: #eaeaea;
  border-radius: 5px;
  margin-bottom: 20px;
  }

.modal-footer {
display: flex;
justify-content: flex-end;
}

.modal-footer button {
margin-left: 10px;
}
</style>